package faq

import (
	"errors"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"time"
)

/**
Frequently Asked Questions as FAQ
*/
type Faq struct {
	Id           int64     `json:"id"`
	ContentLink  string    `json:"content"`
	Title        string    `json:"title"`
	CreateTime   time.Time `json:"create_time"`
	Department   string    `json:"department"`
	DepartmentId int64     `json:"department_id"`
	Order        int       `json:"order"` //排序
}

/**
常见问题-插入
*/
func InsertFaq(faq *Faq) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	sessionInstance.Begin()
	if _, err := sessionInstance.Insert(faq); err != nil {
		sessionInstance.Rollback()
		global.Log.Sugar().Error("插入常见问题失败", err)
		return errors.New("插入常见问题失败")
	}
	sessionInstance.Commit()
	return nil
}

/**
常见问题-更新
*/
func updateFaq(faq *Faq) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	sessionInstance.Begin()
	if _, err := sessionInstance.Where("id = ?", faq.Id).Update(faq); err != nil {
		sessionInstance.Rollback()
		return err
	}
	sessionInstance.Commit()
	return nil
}

/**
常见问题-插入更新
*/
func PutFaq(faq *Faq) error {
	faq.CreateTime = time.Now()
	if faq.Id != 0 {
		return updateFaq(faq)
	} else {
		faq.Id = util.GenSnowflakeInt64()
		return InsertFaq(faq)
	}
}

/**
常见问题-删除
*/
func DelFaq(faqId int64) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	sessionInstance.Begin()
	if _, err := sessionInstance.Where("id = ?", faqId).Delete(new(Faq)); err != nil {
		sessionInstance.Rollback()
		return err
	}
	sessionInstance.Commit()
	return nil
}

/**
常见问题-列表 置顶order=1，其他为0；先按order逆序，再按时间逆序
*/
func GetFaq(id, departmentid int64, page, pagesize int) (int, []*Faq, error) {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	offset := (page - 1) * pagesize
	if id != 0 {
		sessionInstance = sessionInstance.And("id=?", id)
	}
	if departmentid != 0 {
		sessionInstance = sessionInstance.And("department_id=?", id)
	}
	if pagesize == 0 {
		pagesize = 10
	}
	templates := []*Faq{}
	count, err := sessionInstance.
		Desc("order").
		Desc("create_time").
		Limit(pagesize, offset).
		FindAndCount(&templates)
	if err != nil {
		return 0, nil, err
	}
	return int(count), templates, nil
}
